/**
 * 权限管理
 */
Ext.onReady(function() {
	RuleStore = Ext.extend(Ext.data.Store, {
				constructor : function() {
					RuleStore.superclass.constructor.call(this, {
								reader : this.ruleReader,
								proxy : new Ext.data.HttpProxy({
											url : 'getRuleFunction.do',
											method : 'POST'
										})
							})
				},
				ruleReader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'data'
						}, [{
									name : 'ruleId'
								}, {
									name : 'ruleName'
								}, {
									name : 'functionName'
								}])
			});

	RuleSearchTbar = Ext.extend(Ext.Toolbar, {
				constructor : function() {
					RuleSearchTbar.superclass.constructor.call(this, {
								items : ['角色名称：', {
											xtype : 'textfield',
											name : 'rulename',
											width : 100
										}, '-', {
											text : "查询",
											iconCls : 'icon-search',
											tooltip : '查询记录',
											handler : this.onSerchClick,
											scope : this
										}]
							});
					this.addEvents('onSerchClick');
				},
				onSerchClick : function() {
					this.fireEvent('onSerchClick', this);
				}
			});
	RuleSearchPanel = Ext.extend(Ext.form.FormPanel, {
				ruleSearchTbar : null,
				constructor : function() {
					this.ruleSearchTbar = new RuleSearchTbar();
					RuleSearchPanel.superclass.constructor.call(this, {
								defaultType : 'textfield',
								border : false,
								frame : false,
								items : [this.ruleSearchTbar]
							});
				}
			});
	// 功能栏
	RuleBtn = Ext.extend(Ext.Toolbar, {
				constructor : function() {
					RuleBtn.superclass.constructor.call(this, {
								items : [/*
											 * { text : '浏览', iconCls :
											 * 'icon-view', handler :
											 * this.onView, scope : this }, '-',
											 */{
											text : '添加',
											iconCls : 'icon-add',
											handler : this.onAdd,
											scope : this
										}, '-', {
											text : '修改',
											iconCls : 'icon-edit',
											handler : this.onEdit,
											scope : this
										}, '-', {
											text : '删除',
											iconCls : 'icon-remove',
											handler : this.onDelete,
											scope : this
										}]
							}), this.addEvents('onView');
					this.addEvents('onAdd');
					this.addEvents('onEdit');
					this.addEvents('onDelete');
				},
				onAdd : function() {
					this.fireEvent('onAdd', this);
				},
				onEdit : function() {
					this.fireEvent('onEdit', this);
				},
				onDelete : function() {
					this.fireEvent('onDelete', this);
				},
				onView : function() {
					this.fireEvent('onView', this);
				}
			});

	RuleFormPanel = Ext.extend(Ext.form.FormPanel, {
		constructor : function() {
			RuleFormPanel.superclass.constructor.call(this, {
				width : 600,
				height : 200,
				frame : true,
				labelWidth : 100,
				labelAlign : "right",
				url : 'saveRule.do',
				method : 'POST',
				items : [{
							xtype : "textfield",
							name : "ruleId",
							inputType : "hidden"
						}, {
							xtype : "textfield",
							enableKeyEvents : true,
							fieldLabel : "名称",
							name : "functionName",
							allowBlank : false,
							listeners : {
								'keyup' : function(com) {
									Ext.Ajax.request({
										url : 'isRoleNameExit.do',
										params : {
											name : com.getValue()
										},
										method : "post",
										success : function(response) {
											var result = Ext.decode(response.responseText);
											if(result.success){
												Ext.getCmp('submit').enable();
											}else{
												Ext.ux.Toast.msg('信息提示', '此角色名已存在!');
												  Ext.getCmp('submit').disable();
											     com.focus();
											     return;
											}
											
										},
										failure : function(form, action) {
											Ext.ux.Toast.msg('信息提示', '此角色名已存在!');
											com.focus();
										}
									});
								}
							}
						}]
			});
		}
	});

	RuleWin = Ext.extend(Ext.Window, {
		ruleFormPanel : null,
		constructor : function() {
			this.ruleFormPanel = new RuleFormPanel();
			RuleWin.superclass.constructor.call(this, {
						layout : "fit",
						modal : true,
						autoScroll : true, // 滚动条
						buttonAlign : "center", // 按钮居中
						resizable : false,
						items : this.ruleFormPanel,
						buttons : [{
									text : '确定',
									id : 'submit',
									handler : this.onSubmitClick,
									scope : this
								}, {
									text : '取消',
									handler : function() {
										this.close();
									},
									scope : this
								}]
					});
			this.addEvents('submit');
		},
		reset : function() {
			this.ruleFormPanel.getForm().reset();
		},
		onSubmitClick : function() {
			if (this.ruleFormPanel.form.isValid())
				this.fireEvent('submit', this, this.ruleFormPanel);
			else
				Ext.Msg.alert('提示信息', "表单验证不通过");
		},
		load : function(id) {

			var self = this;
			this.ruleFormPanel.getForm().load({
				url : 'loadRole.do?id=' + id,
				waitMsg : '正在载入数据...',
				method : 'POST',
				success : function(form, action) {
					console.log(action);
					var result = Ext.decode(action);
					console.log(result);
					/*
					 * for (var i = 0; i < result.length; i++) { var _checkbox =
					 * new Ext.form.Checkbox({ name : result[i].functionCode,
					 * boxLabel : result[i].functionName, inputValue :
					 * result[i].functionId, checked : false });
					 * this.addRuleWin.ruleFormPanel.add(_checkbox); }
					 */
					self.show();
				},
				failure : function(form, action) {
					var result = Ext.decode(action.response.responseText);
					var funcs = result.functions;
					var checkboxgroup = new CheckBoxGroup()
					for (var i = 0; i < funcs.length; i++) {
						checkboxgroup.items[i] = new Ext.form.Checkbox({
									name : funcs[i].functionCode,
									boxLabel : funcs[i].functionName,
									inputValue : funcs[i].functionId,
									checked : funcs[i].functionUrl == null
											? false
											: funcs[i].functionUrl
								});

					}
					self.ruleFormPanel.add(checkboxgroup);
					self.ruleFormPanel.findByType("textfield")[0].value = result.ruleId;
					self.ruleFormPanel.findByType("textfield")[1].value = result.ruleName;
					self.show();
				}
			})
		}
	});
	AddRuleWin = Ext.extend(RuleWin, {
				title : '新增角色'
			});
	EditRuleWin = Ext.extend(RuleWin, {
				title : '修改角色'
			});
	CheckBoxGroup = Ext.extend(Ext.form.CheckboxGroup, {
				constructor : function() {
					CheckBoxGroup.superclass.constructor.call(this, {
								id : "funccheck",
								columns : 3,
								fieldLabel : '选择菜单',
								items : [{}]
							});
				}
			});
	RuleGridPanel = Ext.extend(Ext.grid.GridPanel, {
		title : '▪ 您现在所在的位置：权限管理',
		ruleSearchPanel : null,
		ruleStore : null,
		ruleBtn : null,
		addRuleWin : null,
		editRuleWin : null,
		constructor : function() {
			this.ruleSearchPanel = new RuleSearchPanel();
			this.ruleStore = new RuleStore();
			this.ruleBtn = new RuleBtn();
			// this.addRuleWin = new AddRuleWin();
			// this.editRuleWin = new EditRuleWin();
			RuleGridPanel.superclass.constructor.call(this, {
						border : false,
						renderTo : Ext.getBody(),
						tbar : this.ruleSearchPanel,
						viewConfig : {
							forceFit : true
						},
						stripeRows : true,// 斑马线
						colModel : new Ext.grid.ColumnModel([this.ruleCSM, {
									// header : "id",
									sortable : true,
									hidden : true,
									width : 100,
									dataIndex : 'ruleId',
									align : 'center'
								}, {
									header : "名称",
									width : 100,
									sortable : true,
									dataIndex : 'ruleName',
									align : 'center'
								}, {
									header : "菜单",
									width : 100,
									sortable : true,
									dataIndex : 'functionName',
									align : 'center'
								}]),
						sm : this.ruleCSM,
						store : this.ruleStore,
						bbar : new Ext.PagingToolbar({
									pageSize : 20,
									store : this.ruleStore,
									displayInfo : true,
									displayMsg : "显示第{0}-{1}条记录，一共{2}条记录",
									emptyMsg : "没有记录"
								}),
						listeners : {
							render : function() {
								this.ruleBtn.render(this.tbar);
								this.initLoad();
							}
						}
					});
			this.ruleSearchPanel.ruleSearchTbar.on('onSerchClick',
					this.loadList, this);
			this.ruleBtn.on('onAdd', this.onAdd, this);
			this.ruleBtn.on('onEdit', this.onEdit, this);
			this.ruleBtn.on('onDelete', this.onDelete, this);
			this.ruleBtn.on('onView', this.onView, this);

		},
		ruleCSM : new Ext.grid.CheckboxSelectionModel(),
		loadList : function() {
			var params = this.ruleSearchPanel.getForm().getValues();
			this.ruleStore.baseParams = {
				name : params.rulename
			}
			this.ruleStore.load({
						params : {
							start : 0,
							limit : 20
						}
					})
		},
		initLoad : function() {
			this.ruleStore.load({
						params : {
							start : 0,
							limit : 20
						}
					})
		},
		reLoad : function() {
			this.ruleStore.reload();
		},
		onAdd : function() {
			Ext.Ajax.request({
				url : "getMenuFunction.do",
				method : "POST",
				success : function(response, action) {
					this.addRuleWin = new AddRuleWin();
					this.addRuleWin.on('submit', this.insertUpdateRecord, this);
					var result = Ext.decode(response.responseText);
					var checkboxgroup = new CheckBoxGroup();
					for (var i = 0; i < result.length; i++) {
						checkboxgroup.items[i] = new Ext.form.Checkbox({
									name : result[i].functionCode,
									boxLabel : result[i].functionName,
									inputValue : result[i].functionId,
									checked : false
								});
						this.addRuleWin.ruleFormPanel.add(checkboxgroup);
					}
					this.addRuleWin.show();
				},
				scope : this
			})

		},
		onEdit : function() {
			if (this.getSelectionModel().getCount() == 0) { // 一条都没选
				Ext.Msg.alert('信息提示', '您未选择任何记录，请选择要修改的记录!');
			} else if (this.getSelectionModel().getCount() > 1) {
				Ext.Msg.alert('信息提示', '您选择了多条记录，一次只能修改一条记录!');
			} else {
				var record = this.getSelectionModel().getSelected();
				var id = record.get("ruleId");
				this.editRuleWin = new EditRuleWin();
				this.editRuleWin.on('submit', this.insertUpdateRecord, this);
				this.editRuleWin.load(id);
			}
		},
		onDelete : function() {
			if (this.getSelectionModel().getCount() == 0) { // 一条都没选
				Ext.Msg.alert('信息提示', '您未选择任何记录，请选择要删除的记录!');
			} else {
				var self = this;
				var record = this.getSelectionModel().getSelections();
				var ids = new Array(record.length);
				for (var i = 0; i < record.length; i++) {
					ids[i] = record[i].get('ruleId');
				}
				Ext.Msg.alert('删除确认', '您确认要删除记录吗？按是将删除选中的记录！', function(btn) {
							if (btn == 'no') {
								return;
							}
							self.del(ids);
						})
			}
		},
		del : function(ids) {
			var self = this;
			Ext.Ajax.request({
						url : 'delRule.do',
						params : {
							ids : ids
						},
						method : "post",
						success : function(response) {
							var result = eval('(' + response.responseText + ')');
							if (result.success) {
								self.reLoad();
							} else {
								Ext.ux.Toast.msg('提示信息', result.msg);
							}
						},
						failure : function(form, action) {
							Ext.ux.Toast.msg('提示信息', "删除信息失败！");
						}
					});
		},
		insertUpdateRecord : function(_win, _form) {
			var self = this;
			var params = _form.getForm().getValues();
			var checkboxs = Ext.getCmp('funccheck');
			var checkedArray = [];
			for (var i = 0; i < checkboxs.items.length; i++) {
				var checkbox = checkboxs.items.items[i];
				if (checkbox.checked) {
					checkedArray.push(checkbox.inputValue)
				}
			}
			if (checkedArray.length == 0) {
				Ext.Msg.alert('提示信息', "请为该用户分配菜单功能！");
				return;
			}
			params.checkedValue = checkedArray.toString();
			_form.form.submit({
						params : params,
						waitTitle : "请稍等",
						waitMsg : "正在保存您的信息",
						success : function(form, action) {
							if (action.result.success) {
								_win.close();
								self.reLoad();
							}
						}
					});
		}
	});
	new Ext.Viewport({
				layout : 'fit',
				items : new RuleGridPanel()
			})

});